/*
 * systimer.cpp
 *
 *  Created on: Oct 29, 2015
 *      Author: rpi
 */

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <string.h>
#include <errno.h>

#define SIG_SYSTEM_TICK               (SIGRTMAX - 1)

volatile unsigned long   g_dwTimerTick  = 0;
timer_t  g_tickTimerId;

const int CLKTICK_PER_MS = 10;
const int CLKTICKS_PER_SEC = (1000/CLKTICKS_PER_SEC);
const int CLKTICKS_PER_MINUTE = (CLKTICKS_PER_SEC*60);
const int CLKTICKS_PER_HOUR = (CLKTICKS_PER_MINUTE*60);
const int CLKTICKS_PER_DAY = (CLKTICKS_PER_HOUR*24);

extern "C" void clkTickIsrHook(int para)
{
//	GdwInIsr++;

	// increment global tick count(s)
	g_dwTimerTick++;

//	GdwInIsr--;
}

void initTimeTick()
{
	struct sigevent    tickEvt;
	struct itimerspec  timeout;

	memset( &tickEvt, 0, sizeof(tickEvt));
	tickEvt.sigev_notify = SIGEV_SIGNAL;
	tickEvt.sigev_signo = SIG_SYSTEM_TICK;
	tickEvt.sigev_value.sival_ptr = 0;

	signal(SIG_SYSTEM_TICK, clkTickIsrHook);

	if ( timer_create( CLOCK_REALTIME, &tickEvt, &g_tickTimerId ) != 0 )
	{
		printf("ERROR: Failed to create system clock timer. error = %d\r\n", errno);
		exit(-1);
	}

	timeout.it_value.tv_sec = 0;
	timeout.it_value.tv_nsec =CLKTICK_PER_MS*1000*1000;

	timeout.it_interval.tv_sec = 0;
	timeout.it_interval.tv_nsec = timeout.it_value.tv_nsec;

	if ( timer_settime( g_tickTimerId, 0, &timeout, NULL ) != 0 )
	{
		printf("ERROR:Failed to start system clock timer. error = %d\r\n", errno);
		timer_delete(g_tickTimerId);
		exit(-1);
	}
}


